package com.haoshuang.zhouzhoubang.ui.page.mine

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import cn.jpush.android.webview.bridge.HostJsScope.click
import com.haoshuang.zhouzhoubang.MyApp
import com.haoshuang.zhouzhoubang.R
import com.haoshuang.zhouzhoubang.databinding.FragmentMineBinding
import com.haoshuang.zhouzhoubang.model.bean.CooperationTimeBean
import com.haoshuang.zhouzhoubang.model.bean.HomeDataBean
import com.haoshuang.zhouzhoubang.ui.activity.FeedBackActivity
import com.haoshuang.zhouzhoubang.ui.activity.MemberManagerActivity
import com.haoshuang.zhouzhoubang.ui.activity.OrderWcActivity
import com.haoshuang.zhouzhoubang.ui.activity.PushOrder2Activity
import com.haoshuang.zhouzhoubang.ui.activity.ServiceLogActivity2
import com.haoshuang.zhouzhoubang.ui.activity.TeamBzActivity
import com.haoshuang.zhouzhoubang.ui.activity.ZsmActivity
import com.haoshuang.zhouzhoubang.ui.dialog.CallDialog
import com.haoshuang.zhouzhoubang.ui.page.data.DataStatisticsActivity
import com.haoshuang.zhouzhoubang.ui.page.home.settings.StoreSettingsActivity
import com.haoshuang.zhouzhoubang.ui.page.home.settings.skill.add.AddSkillListActivity
import com.haoshuang.zhouzhoubang.ui.page.mine.contract.MyContractActivity
import com.haoshuang.zhouzhoubang.ui.page.mine.info.MineUserInfoActivity
import com.haoshuang.zhouzhoubang.ui.page.mine.integral.StoreIntegralActivity
import com.haoshuang.zhouzhoubang.ui.page.mine.notice.list.NoticeListActivity
import com.haoshuang.zhouzhoubang.ui.page.mine.settings.SettingsActivity
import com.haoshuang.zhouzhoubang.ui.page.mine.wallet.MyWalletActivity
import com.haoshuang.zhouzhoubang.ui.page.settled.pay.AnnualFeePayActivity
import com.haoshuang.zhouzhoubang.ui.page.shop.ShoppingActivity
import com.haoshuang.zhouzhoubang.ui.page.shop.order.ShopOrderActivity
import com.haoshuang.zhouzhoubang.ui.page.welfare.PlatformWelfareHomeActivity
import com.lnkj.jialubao.utils.AccountUtils
import com.lxj.xpopup.XPopup
import com.mufeng.libs.base.BaseVMFragment
import com.mufeng.libs.state.observeState
import com.mufeng.libs.utils.ktx.formatMaxNum
import com.mufeng.libs.utils.ktx.toDateForm
import com.mufeng.libs.utils.startPage
import com.mufeng.libs.utils.startPageForResult
import com.mufeng.libs.utils.toast
import com.mufeng.libs.utils.view.click
import com.mufeng.libs.utils.view.clickWithTrigger
import com.mufeng.libs.utils.view.gone
import com.mufeng.libs.utils.view.load
import com.mufeng.libs.utils.view.visible
import com.mufeng.libs.utils.view.visibleOrGone
import java.util.Date

/**
 *
 */
class MineFragment : BaseVMFragment<MineViewModel, FragmentMineBinding>() {

    private var homeData: HomeDataBean? = null

    companion object {
        fun getInstance(): MineFragment {
            val fragment = MineFragment()
            fragment.arguments = Bundle().apply {

            }
            return fragment
        }
    }

    // 合作期限列表
    private val cooperationTimeList = arrayListOf<CooperationTimeBean>()

    override fun initView(savedInstanceState: Bundle?) {

        binding.ivQrcode.click {
            if (homeData?.status != "8") {
                toast("请先入驻")
                return@click
            }
            // 打开专属码
            startPage<ZsmActivity>()
        }

        binding.cevSettings.click {
            // 设置
            startPage<SettingsActivity>()
        }

        // 编辑资料
        binding.tvEdit.click {
            if (homeData?.status != "8") {
                toast("请先入驻")
                return@click
            }
            startPageForResult<MineUserInfoActivity> { code, data ->
                if (code == 200) {
                    vm.getStoreUserInfo()
                }
            }
        }

        // 续费
        binding.tvTeamStateDetail.click {
            if (homeData?.status != "8") {
                toast("请先入驻")
                return@click
            }
            // 续费
            vm.getCooperationPeriod(AccountUtils.user?.city_name)
        }

        // 推送订单
        binding.llPushOrder.click {
            if (homeData?.status != "8") {
                toast("请先入驻")
                return@click
            }
            // 推送订单
            startPage<PushOrder2Activity>()
        }

        // 服务订单
        binding.llServiceOrder.click {
            if (homeData?.status != "8") {
                toast("请先入驻")
                return@click
            }
            // 服务订单
            startPage<OrderWcActivity>()
        }

        // 评价记录
        binding.cevCommentRecord.click {
            if (homeData?.status != "8") {
                toast("请先入驻")
                return@click
            }
            // 评价记录
            startPage<ServiceLogActivity2>()
        }

        // 门店积分
        binding.llStorePoints.click {
            if (homeData?.status != "8") {
                toast("请先入驻")
                return@click
            }
            startPage<StoreIntegralActivity>()
        }

        // 服务类别
        binding.cevServiceKill.clickWithTrigger {
            if (homeData?.status != "8") {
                toast("请先入驻")
                return@clickWithTrigger
            }
            startPage<AddSkillListActivity>()
        }

        // 我的合同
        binding.cevMyContract.click {
            if (homeData?.status != "8") {
                toast("请先入驻")
                return@click
            }
            // 我的合同
            startPage<MyContractActivity>()
        }

        // 意见反馈
        binding.cevFeedback.click {
            // 意见反馈
            startPage<FeedBackActivity>()
        }

        // 联系客服
        binding.cevCustomerService.click {
            // 联系客服
            if (MyApp.systemConfig?.tel.isNullOrBlank()) {
                toast("客服没有留电话,暂时无法拨打")
                return@click
            }

            XPopup.Builder(mActivity)
                .asCustom(CallDialog(mActivity, MyApp.systemConfig?.tel ?: "") {
                    var intent = Intent(Intent.ACTION_DIAL);
                    intent.setData(Uri.parse("tel:${MyApp.systemConfig?.tel}"));
                    startActivity(intent);
                })
                .show()
        }

        // 商城中心
        binding.tvGotoShop.clickWithTrigger {
            startPage<ShoppingActivity>()
        }

        // 平台福利
        binding.llFuli.clickWithTrigger {
            if (homeData?.status != "8") {
                toast("请先入驻")
                return@clickWithTrigger
            }
            // 平台福利
            startPage<PlatformWelfareHomeActivity>()
        }
        // 点击统计
        binding.llStatistics.clickWithTrigger {
            if (homeData?.status != "8") {
                toast("请先入驻")
                return@clickWithTrigger
            }
            startPage<DataStatisticsActivity>()
        }


        // 数据中心
        binding.llDataCenter.clickWithTrigger {
            if (homeData?.status != "8") {
                toast("请先入驻")
                return@clickWithTrigger
            }
            startPage<DataStatisticsActivity>()
        }

        // 门店设置
        binding.llStoreSettings.clickWithTrigger {
            if (homeData?.status != "8") {
                toast("请先入驻")
                return@clickWithTrigger
            }
            startPage<StoreSettingsActivity>()
        }

        binding.llMyWallet.clickWithTrigger {
            if (homeData?.status != "8") {
                toast("请先入驻")
                return@clickWithTrigger
            }
            // 我的钱包
            startPage<MyWalletActivity>()
        }
        binding.llEarnestMoney.clickWithTrigger {
            if (homeData?.status != "8") {
                toast("请先入驻")
                return@clickWithTrigger
            }
            // 保证金
            startPage<TeamBzActivity>()
        }

        binding.llMemberManager.clickWithTrigger {
            if (homeData?.status != "8") {
                toast("请先入驻")
                return@clickWithTrigger
            }
            // 成员管理
            startPage<MemberManagerActivity>()
        }

        // 全部订单 "全部", "待付款", "待发货", "待收货", "已完成"
        binding.llShopOrderAll.clickWithTrigger {
            startPage<ShopOrderActivity>("type" to 0)
        }

        // 待付款
        binding.llShopOrder1.clickWithTrigger {
            startPage<ShopOrderActivity>("type" to 1)
        }

        // 待发货
        binding.llShopOrder2.clickWithTrigger {
            startPage<ShopOrderActivity>("type" to 2)
        }

        // 待收货
        binding.llShopOrder3.clickWithTrigger {
            startPage<ShopOrderActivity>("type" to 3)
        }

        // 已完成
        binding.llShopOrder4.clickWithTrigger {
            startPage<ShopOrderActivity>("type" to 4)
        }

        // 平台公告
        binding.llNotice.clickWithTrigger {
            startPage<NoticeListActivity>()
        }
    }

    override fun initData() {

    }

    override fun lazyLoadData() {

    }

    override fun onResume() {
        super.onResume()
        vm.getHomeData()
        vm.getStoreUserInfo()
    }

    override fun startObserve() {

        vm.getStoreUserInfoData.observeState(this) {
            onSuccess {
                AccountUtils.user = it?.data
                setMineData()
            }
        }

        vm.getHomeDataData.observeState(this) {
            onSuccess {
                homeData = it?.data
                // 总收入
                binding.tvTotalIncome.text = homeData?.total_income ?: "0.0"
                // 订单数
                binding.tvOrderNum.text = homeData?.order_total ?: "0"
                // 积分
                binding.tvIntegral.text = AccountUtils.user?.team?.team_integral ?: "0"
                // 总营业额
                binding.tvTurnover.text = homeData?.order_total_amount ?: "0.0"

                binding.viewShopOrder1.visibleOrGone(homeData?.goods_order?.unpay_goods_order_count != 0)
                binding.viewShopOrder1.text = homeData?.goods_order?.unpay_goods_order_count.formatMaxNum(9)
                binding.viewShopOrder2.visibleOrGone(homeData?.goods_order?.wait_goods_order_count != 0)
                binding.viewShopOrder2.text = homeData?.goods_order?.wait_goods_order_count.formatMaxNum(9)
                binding.viewShopOrder3.visibleOrGone(homeData?.goods_order?.received_goods_order_count != 0)
                binding.viewShopOrder3.text = homeData?.goods_order?.received_goods_order_count.formatMaxNum(9)
                binding.viewShopOrder4.visibleOrGone(homeData?.goods_order?.finish_goods_order_count != 0)
                binding.viewShopOrder4.text = homeData?.goods_order?.finish_goods_order_count.formatMaxNum(9)
            }
        }

        vm.getCooperationPeriodData.observeState(this) {
            onSuccess {
                cooperationTimeList.clear()
                cooperationTimeList.addAll(it?.data ?: mutableListOf())
                if (cooperationTimeList.isNotEmpty()) {
                    XPopup.Builder(mActivity)
                        .asBottomList(
                            "选择合作期限",
                            cooperationTimeList.map { "${it.exp} - ${it.join_year}年/${it.join_money}元" }
                                .toTypedArray()
                        ) { position, text ->
                            val year = cooperationTimeList[position].join_year
                            val yearMoney = cooperationTimeList[position].join_money
                            startPage<AnnualFeePayActivity>(
                                "year" to year,
                                "fee" to yearMoney.toString()
                            )
                        }
                        .show()
                }
            }
        }

    }

    private fun setMineData() {
        val user = AccountUtils.user
        val team = user?.team
        if (user?.status == "8") {
            binding.rivHead.load(
                team?.team_logo,
                placeholder = R.mipmap.logo,
                error = R.mipmap.logo
            )
            binding.tvTeamName.text = team?.team_name
        } else {
            binding.rivHead.load(
                user?.avatar,
                placeholder = R.mipmap.logo,
                error = R.mipmap.logo
            )
            binding.tvTeamName.text = user?.nickname
        }
        if (team?.team_name.isNullOrEmpty() || team?.team_logo.isNullOrEmpty() || user?.team_company_pic.isNullOrEmpty() || user?.synopsis.isNullOrEmpty()) {
            binding.tvEdit.text = "待完善"
        } else {
            binding.tvEdit.text = "去编辑"
        }

        if (team?.team_end_time?.isNotEmpty() == true && homeData?.status == "8") {
            binding.llTeamTime.visible()
            val end = team.team_end_time.toDateForm("yyyy-MM-dd")!!
            val now = Date()
            if (end.time > now.time) {
                binding.tvTeamState.text = "门店到期时间: ${team?.team_end_time}"
            } else {
                binding.tvTeamState.text = "门店已到期"
            }
            binding.tvTeamStateDetail.text = "续费"
        } else {
            binding.llTeamTime.gone()
            binding.tvTeamState.text = "门店状态：资料确认"
            binding.tvTeamStateDetail.text = "查看资料"
        }

        // 推送订单数
        binding.tvPushOrderNum.text = team?.tui_order_num.toString()
        // 服务订单数
        binding.tvServiceOrderNum.text = team?.complete_order_num.toString()
        // 免服务费
        binding.tvFeeOrderNum.text = team?.fee_order_num.toString()
    }

}